package com.jumi.microservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.common.utils.EnumUtil;
import com.jumi.microservice.domain.MessageTemplate;
import com.jumi.microservice.dto.reponse.JmUserReponse;
import com.jumi.microservice.dto.wallet.api.WalletInOrOutListRequest;
import com.jumi.microservice.dto.wallet.api.WalletInOrOutListResponse;
import com.jumi.microservice.dto.wallet.api.WalletInOrOutRequest;
import com.jumi.microservice.entity.UserWallet;
import com.jumi.microservice.enumerate.WalletTypeEnum;
import com.jumi.microservice.enums.FenXiaoType;
import com.jumi.microservice.mapper.UserWalletMapper;
import com.jumi.microservice.rocketmq.SendMessageHandler;
import com.jumi.microservice.service.admin.AdminCapitalDetailsService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by mazhao
 * @Classname WalletInOrOutService
 * @Description TODO
 * @Date 2020/7/22 10:47
 */
@DubboService(interfaceClass = IWalletInOrOutService.class)
public class WalletInOrOutServiceImpl implements IWalletInOrOutService {

    @Resource
    UserWalletMapper userWalletMapper;
    @Resource
    SendMessageHandler sendMessageHandler;
    @DubboReference
    IMemberService iMemberService;
    @Resource
    AdminCapitalDetailsService adminCapitalDetailsService;
    @Resource
    RedisTemplate<String,String> redisTemplate;

    public static final String userLastDayWaitCash = "userLastDayWaitCash::";
    /**
     * 入账
     *
     * @param request
     * @return
     */

    @Override
    public ResponseResult<Boolean> walletIn(WalletInOrOutRequest request) {
        UserWallet userWallet = new UserWallet();
        BeanUtils.copyProperties(request, userWallet);
        if(userWallet.getUserLevel()==null){
            List<Integer> userIds = new ArrayList<>();
            userIds.add(request.getUserId().intValue());
            Map<Long, JmUserReponse> userMap = adminCapitalDetailsService.getUserInfoMap(userIds);
            if(userMap.containsKey(request.getUserId())){
                userWallet.setUserLevel(userMap.get(request.getUserId()).getLevel().getValue());
            }
        }
        if(request.getType().equals(WalletTypeEnum.AFTER_SALE_BCK_IN.getCode())){
            userWallet.setRemark("订单补偿，订单编号："+request.getOrderNo());
        }
        int res = userWalletMapper.insert(userWallet);
        if(res>0 && request.getType().equals(WalletTypeEnum.AFTER_SALE_BCK_IN.getCode())){
            MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(18);
            sendMessage(messageTemplate,request);
        }
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        return responseResult.setData(true);
    }

    /**
     * 用户服务批量入账
     *
     * @param list
     * @return
     */
    @Override
    public Boolean batchWalletIn(List<WalletInOrOutRequest> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        MessageTemplate messageTemplate = sendMessageHandler.getMessageTemplate(20);
        for (WalletInOrOutRequest request : list) {
            UserWallet userWallet = new UserWallet();
            BeanUtils.copyProperties(request, userWallet);
            if (request.getType().equals(FenXiaoType.推广收益.getValue())) {
                userWallet.setType(WalletTypeEnum.SPREAD_IN.getCode());
                userWallet.setRemark(WalletTypeEnum.SPREAD_IN.getMsg() + "，订单编号：" + request.getOrderNo());
            } else if (request.getType().equals(FenXiaoType.服务收益.getValue())) {
                userWallet.setType(WalletTypeEnum.ORDER_IN.getCode());
                userWallet.setRemark(WalletTypeEnum.ORDER_IN.getMsg() + "，订单编号：" + request.getOrderNo());
            }
            int res = userWalletMapper.insert(userWallet);
            if(res>0){
                sendMessage(messageTemplate,request);
            }
        }
        return true;
    }


    /**
     * 组件信息并发送信息
     * @param messageTemplate
     * @param request
     */
    public void sendMessage(MessageTemplate messageTemplate, WalletInOrOutRequest request){
        String appMessageContent = messageTemplate.getSmtAppContent()
                .replace("{walletInAmount}", request.getAmount().toString())
                .replace("{}",request.getOrderNo())
                .replace("{waitCash}", userWalletMapper.WaitCashByUserId(request.getUserId()).toString());
        String stationMessageContent = messageTemplate.getSmtMessageContent()
                .replace("{walletInAmount}", request.getAmount().toString())
                .replace("{}",request.getOrderNo())
                .replace("{waitCash}", userWalletMapper.WaitCashByUserId(request.getUserId()).toString());
        sendMessageHandler.sendMessage(appMessageContent, stationMessageContent, request.getUserId(), messageTemplate.getId().intValue());
    }



    /**
     * 出账
     *
     * @param request
     * @return
     */
    @Override
    public ResponseResult<Boolean> walletOut(WalletInOrOutRequest request) {
        ResponseResult<Boolean> responseResult = new ResponseResult<>();
        UserWallet userWallet = new UserWallet();
        BeanUtils.copyProperties(request, userWallet);
        if(userWallet.getUserLevel()==null){
            List<Integer> userIds = new ArrayList<>();
            userIds.add(request.getUserId().intValue());
            Map<Long, JmUserReponse> userMap = adminCapitalDetailsService.getUserInfoMap(userIds);
            if(userMap.containsKey(request.getUserId())){
                userWallet.setUserLevel(userMap.get(request.getUserId()).getLevel().getValue());
            }
        }
        BigDecimal balance = userWalletMapper.getBalanceByUserId(userWallet.getUserId()).subtract(userWallet.getAmount());
        if (balance.compareTo(BigDecimal.ZERO) < 0) {
            return responseResult.setData(false);
        }
        userWallet.setAmount(userWallet.getAmount().negate());
        return responseResult.setData(userWalletMapper.insert(userWallet) > 0);
    }


    /**
     * 前台获取钱包收支明细
     *
     * @param request
     * @return
     */
    @Override
    public TableDataInfo<List<WalletInOrOutListResponse>> getWalletInOrOutList(WalletInOrOutListRequest request) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        List<WalletInOrOutListResponse> result = new ArrayList<>();
        IPage<UserWallet> page = new Page<>(request.getPageNum(), request.getPageSize());
        QueryWrapper<UserWallet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("user_id", request.getUserId())
                .orderByDesc("create_time");
        IPage<UserWallet> records = userWalletMapper.selectPage(page, queryWrapper);
        List<UserWallet> list = records.getRecords();
        for (UserWallet userWallet : list) {
            WalletInOrOutListResponse walletInOrOutListResponse = new WalletInOrOutListResponse();
            walletInOrOutListResponse.setAmount(userWallet.getAmount());
            WalletTypeEnum walletTypeEnum = EnumUtil.getByCode(userWallet.getType(), WalletTypeEnum.class);
            walletInOrOutListResponse.setDescription(walletTypeEnum.getMsg());
            walletInOrOutListResponse.setTime(userWallet.getCreateTime());
            result.add(walletInOrOutListResponse);
        }
        tableDataInfo.setTotal(records.getTotal());
        tableDataInfo.setRows(result);
        return tableDataInfo;
    }

    @Override
    public BigDecimal waitCash(Long uid) {
        BigDecimal today = userWalletMapper.WaitCashByUserIdToday(uid);
        String key = userLastDayWaitCash.concat(String.valueOf(uid));
        Boolean hasKey = redisTemplate.hasKey(key);
        BigDecimal lastDay;
        if(hasKey!=null && hasKey){
            lastDay = new BigDecimal(redisTemplate.opsForValue().get(key));
        }else{
            lastDay = userWalletMapper.listDayWaitCashByTimeByUid(uid);
            redisTemplate.opsForValue().set(key,lastDay.toString());
        }
        return today.add(lastDay);
    }

    /**
     * 出入账枚举字典
     *
     * @return
     */
    @Override
    public Map<Integer, String> dic() {
        WalletTypeEnum[] walletTypeEnums = WalletTypeEnum.values();
        Map<Integer, String> map = new HashMap<>(walletTypeEnums.length);
        for (WalletTypeEnum walletTypeEnum : walletTypeEnums) {
            map.put(walletTypeEnum.getCode(), walletTypeEnum.getMsg());
        }
        return map;
    }

    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(fixedDelay = 60 * 60 * 1000)
    public void scheduledWallet(){
        List<Map<String,BigDecimal>> listMap = userWalletMapper.listDayWaitCashByTime();
        for(Map<String,BigDecimal> map:listMap){
            redisTemplate.opsForValue().set(userLastDayWaitCash.concat(String.valueOf(map.get("userId"))),
                    String.valueOf(map.get("amount")));
        }
    }

}
